% How many quantiles to sort loans into based on own IRR
% If I use 5, the first quantile would be -5000% & the scale is messed up
% 
N_Quantiles = 3;
N_boots = 500;


%%%%%%%%%%%%%%%%%%
% Only Old Group %
%%%%%%%%%%%%%%%%%%

data = readtable("../data/interim/loanlevelirrOld.csv");

T = max(data.loandayselapsed)+1;
N = height(data)/T;

cf = reshape(data.cf,T,N);

% Calculate IRRs for individual loans

irrbyloan = irr(cf);
irrbyloan(isnan(irrbyloan))=-inf;
irrbyloan = irrbyloan';

% Re-arrange loans

irrbyloan = [irrbyloan [1:length(irrbyloan)]'];
irrbyloan = sortrows(irrbyloan,1);
cf = cf(:,irrbyloan(:,2)');

% Group into quantiles

cf_quantiles = NaN(size(cf,1),N_Quantiles);
for d=1:N_Quantiles
    lowind = ceil(size(cf,2)/N_Quantiles)*(d-1)+1;
    highind = min((ceil(size(cf,2)/N_Quantiles)*d),size(cf,2));
    cf_quantiles(:,d) = sum(cf(:,lowind:highind),2);
end

% IRR by quantiles

irrbyquantiles = irr(cf_quantiles);

% IRR overall

irrall = irr(sum(cf,2));

% Export data for plotting

irrbyloan_Old = irrbyloan;
irrbyquantiles_Old = irrbyquantiles;

%--------------------------%
% Bootstrap & calculate SE %
%--------------------------%

irrbyquantiles_allboots = NaN(N_boots,3);

for i=1:N_boots

    cf_new = cf(:,randsample(1:size(cf,2),size(cf,2),true));

    % Calculate IRRs for individual loans
    
    irrbyloan = irr(cf_new);
    irrbyloan(isnan(irrbyloan))=-inf;
    irrbyloan = irrbyloan';
    
    % Re-arrange loans
    
    irrbyloan = [irrbyloan [1:length(irrbyloan)]'];
    irrbyloan = sortrows(irrbyloan,1);
    cf_new = cf_new(:,irrbyloan(:,2)');
    
    % Group into quantiles
    
    cf_quantiles = NaN(size(cf_new,1),N_Quantiles);
    for d=1:N_Quantiles
        lowind = ceil(size(cf_new,2)/N_Quantiles)*(d-1)+1;
        highind = min((ceil(size(cf_new,2)/N_Quantiles)*d),size(cf_new,2));
        cf_quantiles(:,d) = sum(cf_new(:,lowind:highind),2);
    end
    
    % IRR by quantiles
    
    irrbyquantiles_oneboot = irr(cf_quantiles);

    irrbyquantiles_allboots(i,:) = irrbyquantiles_oneboot;

end

irrbyquantiles_allboots_Old = irrbyquantiles_allboots;

%--------------------%
% Export the outputs %
%--------------------%

save("../data/interim/irrbyquantiles_allboots_Old.mat",'irrbyquantiles_allboots_Old');
save("../data/interim/irrbyloan_Old.mat",'irrbyloan_Old');

